<template>
  <div class="box-content money-re">
    <div class="navigation">财务管理/财务明细</div>
    <!--搜索-->
    <div class="mt-3">
      <div>
        <div>
          <el-date-picker
                  class="mrt-10"
                  style="width: 350px;"
                  v-model="acount.date"
                  type="daterange"
                  @change="handleChangeDate"
                  range-separator="~"
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
          <user-search class="w-25 " @changeName="changeNameSearch"></user-search>
        </div>
        <div class="box-money">
          <div class="box-money-box" v-loading="loadingMoney">
            <div class="box-money-box-span">
              <img src="@/assets/imgs/money.png" alt="" class="img">
              <span>累计充值</span>
            </div>
            <div >￥<span style="font-size: 30px">{{acountList.recharge}}</span>元</div>
          </div>
          <div class="box-money-box marl" v-loading="loadingMoney">
            <div class="box-money-box-span">
              <img src="@/assets/imgs/purse.png" alt="" class="img">
              <span>累计消费</span>
            </div>
            <div>￥<span style="font-size: 30px">{{acountList.buy}}</span>元</div>
          </div>
        </div>
      </div>
      <div style="margin-top: 30px">
        <user-search class="w-25 mrt-10" @changeName="changeName"></user-search>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="success" class="mx-4" @click="recharge">充值</el-button>
      </div>
    </div>
    <!--表格-->
    <div class="mt-3">
      <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="充值" name="recharge"></el-tab-pane>
        <el-tab-pane label="用户消费" name="buy"></el-tab-pane>
        <el-tab-pane label="管理员扣除" name="reduce"></el-tab-pane>
      </el-tabs>
      <el-table
              :data="rechargeData"
              v-loading="loading"
              align="center"
              :element-loading-text="loadText"
              :header-cell-style="tableHeaderColor"
              stripe
              style="width: 100%">
        <el-table-column
                prop="id"
                align="center"
                label="编号"
                width="80"
        >
        </el-table-column>

        <el-table-column
                prop="price"
                align="center"
                label="金额"
        >
        </el-table-column>
        <el-table-column
                prop="type_link"
                align="center"
                label="方式"
        >
        </el-table-column>
        <el-table-column
                prop="user.name"
                align="center"
                label="商户/电话"
        >
          <template slot-scope="scope">
            <div align="center" v-if="scope.row['user']">{{scope.row['user']['name']?scope.row['user']['name'] + '/' + scope.row['user']['phone']:'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                prop="pay_user.name"
                align="center"
                label="操作人"
        >
        </el-table-column>
        <el-table-column
                label="时间"
                align="center"
                width="100">
          <template slot-scope="scope">
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <!--<el-table-column-->
                <!--label="状态/操作"-->
                <!--align="center"-->
                <!--fixed="right"-->
                <!--width="160"-->
        <!--&gt;-->
          <!--<template slot-scope="scope">-->
            <!--<el-button-->
                    <!--size="mini"-->
                    <!--type="primary"-->
                    <!--@click="handleEdit(scope.row)">充值-->
            <!--</el-button>-->
            <!--<el-button-->
                    <!--size="mini"-->
                    <!--type="danger"-->
                    <!--@click="handleDelete(scope.row)">删除-->
            <!--</el-button>-->
          <!--</template>-->
        <!--</el-table-column>-->
      </el-table>
      <div class="mt-3 float-right">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
    <!--新增对话框-->
    <el-dialog :title="dialog.title"
               :visible.sync="dialogFormVisible"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px" v-loading="loadingDialig">
        <el-form-item label="账号" prop="name">
          <el-select
                  v-model="form.name"
                  filterable
                  remote
                  reserve-keyword
                  style="width: 450px;"
                  placeholder="请输入关键词搜索(账号或者手机号)"
                  :remote-method="remoteMethod"
                  :loading="searchLoading">
            <el-option
                    v-for="item in userOption"
                    :key="item.id"
                    :label="item.name + ' ' + item.phone"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" placeholder="请输入金额" style="width: 450px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'充值中':'点击充值'}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import UserSearch from '../../components/UserInfo.vue'
    export default {
        name: "MoneyList",
        components:{
            UserSearch
        },
        data() {
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                } else {
                    callback();
                }
            };
            var validateMoney = (rule, value, callback) => {
                let g = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                if (value === '') {
                    callback(new Error('请输入充值金额'));
                } else{
                    if (!g.test(value)) {
                        callback(new Error('请输入正确金额'));
                    } else{
                        callback();
                    }
                }

            };
            return {
                acountList: {},
                acount:{
                    date:[],
                    userId:null
                },
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                activeName:'all',
                rechargeData: [],
                userOption: [],
                searchLoading: false,
                loadingMoney: false,
                searchStr:'',
                search: {
                    inputName: null
                },
                baseId: null,
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                form: {
                    name:'',
                    money: null
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                rules: {
                    name: [
                        { validator: validateName, trigger: 'change' }
                    ],
                    money: [
                        { validator: validateMoney, trigger: 'change' }
                    ]
                }

            }
        },
        watch: {
            dialogFormVisible:function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                }
            },
            'acount.userId':function (val) {
                this.getLeiJiMoney();
            }
        },

        created() {
            this.getRechargeList();
            this.getMonth();
        },
        methods: {
            handleChangeDate() {
                this.getLeiJiMoney();
            },
            changeName(val) {
                this.search.inputName = val;
            },
            changeNameSearch(val) {
                this.acount.userId = val;
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.searchLoading = true;
                    setTimeout(() => {
                        this.getUserList(query);
                    }, 200);
                } else {
                    this.userOption = [];
                }
            },
            getMonth() {
                // 获取当前月的第一天
                var start = new Date();
                start.setDate(1);

                // 获取当前月的最后一天
                var date = new Date();
                var currentMonth = date.getMonth();
                var nextMonth = ++currentMonth;
                var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
                var oneDay = 1000 * 60 * 60 * 24;
                var end = new Date(nextMonthFirstDay - oneDay);

                var startDate = this.transferDate(start); // 日期变换
                var endDate = this.transferDate(end); // 日期变换
                this.acount.date = [startDate,endDate];
                this.getLeiJiMoney();
                // return [startDate,endDate];/
            },
            transferDate(date) {
                // 年
                var year = date.getFullYear();
                // 月
                var month = date.getMonth() + 1;
                // 日
                var day = date.getDate();

                if (month >= 1 && month <= 9) {

                    month = "0" + month;
                }
                if (day >= 0 && day <= 9) {

                    day = "0" + day;
                }

                var dateString = year + '-' + month + '-' + day;

                return dateString;
            },
            getLeiJiMoney() {
                this.loadingMoney = true;
                let user_id = '';
                if (this.acount.userId) {
                    user_id = '&user_id=' + this.acount.userId
                } else {
                    user_id = '';
                }
                this.$http.get('api/admin/money/countMoney?start_date=' + this.acount.date[0] + '&end_time=' + this.acount.date[1] + user_id)
                    .then((response) => {
                        this.acountList = response.data;
                        this.loadingMoney = false;
                    })
                    .catch((error) => {
                        this.loadingMoney = false;
                        this.$message.warning(error.data.msg || "数据异常，请重试");
                    });
            },
            getUserList(val) {
                let query={};
                if (!val) {
                    query={};
                } else {
                    query['name|phone$'] = '%' + val + '%';
                }
                this.userOption = [];
                this.$http.get('api/admin/common/user', {
                    params: query
                })
                    .then((response) => {
                        this.searchLoading = false;
                        response.data.forEach(item=>{
                            this.userOption.push(item);
                        })
                    })
                    .catch((error) => {
                        this.searchLoading = false;
                        this.$message.warning(error.data.msg || "数据异常，请重试");
                    });
            },
            handleDelete(val){
                this.$confirm('此操作将永久删除此记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/admin/money/record/' + val.id)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                during:1000
                            });
                            this.getRechargeList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleClick(tab) {
                this.pageInfo.current_page = 1;
                this.onSearch();
            },
            recharge(){
                this.dialog.title = '用户充值';
                this.dialogFormVisible = true;
            },
            getRechargeList() {
                this.loading = true;
                this.$http.get('api/admin/money/record' + this.searchStr , {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        this.rechargeData = result.data;
                        this.pageInfo.total = result.meta.total;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.activeName !== 'all') {
                    this.addConStr();
                    this.searchStr += `type=${this.activeName}`;
                }
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `user_id=${this.search.inputName}`;
                }
                this.pageInfo.current_page = 1;
                this.getRechargeList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.rechargeMoney();
                    } else {
                        return false;
                    }
                });
            },
            rechargeMoney(){
                this.loadingCreate = true;
                this.$http.post('api/admin/common/changePrice', {
                    userid: this.form.name,
                    type: 'recharge',
                    price: this.form.money
                })
                    .then((response) => {
                        this.$message({
                            type: 'success',
                            message: '充值成功',
                            during:1000
                        });
                        this.getMonth();
                        this.onSearch();
                        this.dialogFormVisible = false;
                        this.loadingCreate = false;
                    })
                    .catch((error) => {
                        this.loadingCreate = false;
                        this.$message.warning(error.data.msg || "数据异常，请重试");
                    });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getRechargeList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getRechargeList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less">
  .money-re{
    .box-money{
      display: flex;
      margin-top: 20px;
      .box-money-box{
        width: 300px;
        height: 150px;
        border-radius: 6px;
        box-shadow: 0px 2px 10px #999;
        text-align: center;
        padding-top: 20px;
        .box-money-box-span{
          display: flex;
          justify-content: center;
          align-items: center;
          .img{
            width: 40px;
            height: 40px;
          }
        }

      }
      .marl{
        margin-left: 20px;
      }
    }
    .el-tabs--card>.el-tabs__header{
      margin: 0 -10px 10px ;
      padding-left: 10px ;
    }
    .flow{
      font-weight: 400;
      color: rgb(0, 172, 214);
      font-size: 28px;
    }
  }

</style>